package com.ktgj.pay.controller;

import com.ktgj.common.core.web.domain.AjaxResult;
import com.ktgj.pay.payUtil.WechatPayUtil;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Map;

@ControllerAdvice
@RestController
@RequestMapping("weChatPay")
class WeChatPayController {

    @RequestMapping("createNative")
    public AjaxResult createNative(@RequestParam("orderId") Long orderId, @RequestParam("body") String body, @RequestParam("out_trade_no") String out_trade_no, @RequestParam("totalFee") BigDecimal totalFee) {
        return AjaxResult.success(WechatPayUtil.createNative(orderId, body, out_trade_no, totalFee));
    }

    /**
     * 获取微信支付参数(JSAPI)
     * attach 自定义参数
     * money 实际支付金额
     * orderNumber 订单号
     * notifyUrl 回调地址 "http://39.106.54.2:8080/WXPay/orderResult"
     */
    @RequestMapping("getWechatJSAPIPayParam")
    public AjaxResult getWechatJSAPIPayParam(@RequestParam("openId") String openId, @RequestParam("money") BigDecimal money,
                                             @RequestParam("orderNumber") String orderNumber, @RequestParam("notifyUrl") String notifyUrl) throws Exception {
        return AjaxResult.success(WechatPayUtil.getWechatJSAPIPayParam(openId, money, orderNumber, notifyUrl));
    }

    /**
     * 微信退款
     */
    @RequestMapping("refundWechat")
    public AjaxResult refundWechat(@RequestParam("orderNumber") String orderNumber, @RequestParam("refundNumber") String refundNumber,
                             @RequestParam("notifyUrl") String notifyUrl, @RequestParam("refundMoney") BigDecimal refundMoney,
                             @RequestParam("totalMoney") BigDecimal totalMoney) {
        Map<String, String> map = WechatPayUtil.refund(orderNumber, refundNumber, notifyUrl, refundMoney, totalMoney);
        if (map.get("result_code").equals("FAIL"))
        {
            return AjaxResult.error(map.get("err_code_des"));
        }
        if (map == null) {
            return AjaxResult.error("退款申请失败");
        }
        if (map.get("result_code").equals("SUCCESS"))
        {
            return AjaxResult.success(map.get("result_code"));
        }
        return AjaxResult.error("退款失败！");
    }

    @RequestMapping("refundTest")
    public AjaxResult refundTest() {//4200001390202204118904452116
        return AjaxResult.success(this.refundWechat("1513713944559091711", "202203140303470001", "https://weixin.qq.com",
                new BigDecimal(0.01), new BigDecimal(0.01)));
    }

    /**
     * 验证是否通过
     * @param resultMap
     * @return
     */
    @RequestMapping("isPaySuccessful")
    public boolean isPaySuccessful(@RequestBody Map<String, String> resultMap) {
        boolean successful = WechatPayUtil.isPaySuccessful(resultMap);
        return successful;
    }
}
